package com.raph.db;

import com.raph.exception.DbLoadingException;
import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.InputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

public class DbUtils {
    private static final Logger logger = LoggerFactory.getLogger(DbUtils.class);
    private static final HikariDataSource dataSource;

    static {
        try (InputStream input = DbUtils.class.getResourceAsStream("/db-config.properties")) {
            Properties properties = new Properties();
            properties.load(input);
            HikariConfig config = new HikariConfig();
            config.setJdbcUrl(properties.getProperty("jdbc.url"));
            config.setUsername(properties.getProperty("jdbc.username"));
            config.setPassword(properties.getProperty("jdbc.password"));
            config.setMaxLifetime(500);
            config.setLeakDetectionThreshold(2000);
            config.setMaximumPoolSize(20);
            dataSource = new HikariDataSource(config);
            logger.info("============数据库初始化完成============");
        } catch (Exception e) {
            throw new DbLoadingException("数据库加载失败！", e);
        }
    }

    private DbUtils() {
    }

    public static void init(){
        //只是用来触发静态代码块
    }

    public static void close(AutoCloseable...res){
        for(var re : res){
            if(re != null){
                try {
                    re.close();
                } catch (Exception e) {
                    logger.warn("资源释放异常: {}", e.getMessage(), e);
                }
            }
        }
    }

    public static Connection getConnection() {
        try {
            return dataSource.getConnection();
        } catch (SQLException e) {
            logger.error("获取数据库连接失败: {}", e.getMessage(), e);
        }
        return null;
    }
}
